const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
// 连接方式
const server = require('http').createServer(app.callback())
const io = require('socket.io')(server)

app.use(views(__dirname + '/views'))
const router = require('./routes/index')
app.use(router.routes(), router.allowedMethods())




// socket.emit()  // 触发事件
io.on('connection', function(socket) {
  let username = ''
  socket.on('username', function(user) {
    console.log(socket.id)
    io.emit('username', user)
    username = user
  })
  socket.on('msg', function(msg) {
    io.emit('msg', msg, username)
  })
  socket.on('writing', function() {
    // 1.广播给所有客户端
    // io.emit('writing', username)
    // 2.广播给除了自己的其他客户端
    socket.broadcast.emit('writing', username)
    // 3.广播给自己
    // socket.emit('writing', username)
  })
  socket.on('disconnect', function() {
    if (username !== '') {
      io.emit('remove', username)
    }
  })
})

// 监听端口
server.listen(3000, function() {
  console.log('listen on 3000')
})